<template>
  <div>
    <div>
      <span style="font-size: 16px;font-weight: bolder">巡检任务列表</span>
      <Button type="success"
              shape="circle"
              icon="ios-refresh"
              style="font-size: 22px;margin-left: 100px"
              @click="getOnlineSpeaker()"
      ></Button>

      <Badge v-for="(item, index) in online_speaker" :key="index">
        <Dropdown style="margin-left:20px">
          <Avatar :style="{background: item.device_type === 0 ? '#f56a00' : '#7265e6'}">
            {{ item.device_type === 0 ? 'ADB' : '串口' }}
          </Avatar>
          <DropdownMenu slot="list" style="text-align: center">
            <DropdownItem>{{ item.port }}</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Icon type="ios-radio-button-on" slot="count" :color="item.run_status === 1 ? '#ed4014' : '#19be6b'" size="16" />
      </Badge>

      <div style="float: right;margin-right: 10px">
        <ButtonGroup style="margin-left: 20px">
          <Button>全部</Button>
          <Button>运行中</Button>
          <Button>未开始</Button>
          <Button>已完成</Button>
        </ButtonGroup>
      </div>
    </div>
    <div>
      <Button @click="onClickGetProductInfo" type="dashed" long style="margin: 10px auto;height: 40px">
        <span style="font-size: 16px;font-weight: bold">
          <Icon type="ios-add-circle-outline" />
          添加巡检任务
        </span>
      </Button>
    </div>
    <div style="overflow-x: hidden">
      <div v-for="(item, index) in task_list" :key="index">
        <Row type="flex" align="middle" justify="center" :gutter="10">
          <i-col span="2">
            <Avatar style="background-color: #101010" icon="md-paper-plane" size="large"/>
          </i-col>
          <i-col span="2">
            <h2 class="title">{{ item.title }}</h2>
            <p>{{ item.desc }}</p>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="2">
            <p class="title">所属产品</p>
            <p>{{ item.task_type }}</p>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="2">
            <p class="title">创建者</p>
            <p>{{ item.creator }}</p>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="2">
            <p class="title">创建时间</p>
            <p>{{ item.create_time }}</p>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="5">
            <h2 class="title">用例模块</h2>
            <Tag color="default" v-for="(tag, index) in item.modules" :key="index">{{ tag }}</Tag>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="1">
            <p class="title">任务类型</p>
            <Tag color="default" style="height: 22px;line-height: 22px"><p>{{ item.is_smoke ? "冒烟" : "全部" }}</p></Tag>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="2" style="text-align: center;">
            <h2 class="title">任务状态</h2>
            <Tag type="border" :color="select_color(item.status)" style="margin-left: 5px">{{ select_title(item.status) }}</Tag>
          </i-col>
          <Divider type="vertical" style="height: 30px"/>
          <i-col span="3">
<!--            <div>-->
<!--              <Select v-model="item.test_speaker" style="width:280px;margin-bottom: 10px" placeholder="请选择测试音箱">-->
<!--                <Option-->
<!--                    v-for="(key, index) in select_online_speaker(item.sys_version)"-->
<!--                    :key="index"-->
<!--                    :value="key.sn"-->
<!--                    :label="key.sn">-->
<!--                  <span>{{ key.sn }}</span>-->
<!--                  <span style="float:right;color:#ccc">{{ select_title(key.device_type) }}</span>-->
<!--                </Option>-->
<!--              </Select>-->
<!--            </div>-->
            <Button v-if="item.status === 0" type="primary" @click="onClickExecuteTask(item.id)"><Icon type="md-arrow-dropright-circle" /> 开始</Button>
            <Button v-if="item.status === 2" type="success" to="http://api.mydjangoproject.cn:8000/media/banner/allure-report/index.html"><Icon type="md-clock" /> 查看</Button>
            <Button v-if="item.status === 1" type="error" to=""><Icon type="md-close-circle" /> 中断</Button>
          </i-col>
        </Row>
        <Divider style="margin: 13px auto"/>
      </div>
    </div>
    <Modal
        v-model="selectSpeakerModal"
        title="请选择测试音箱"
        width="720"
        :loading="loadingTag"
        @on-ok="executeTask(checkSpeakerPort)">
      <Row style="height: 50px;line-height: 50px">
        <i-col flex="auto">
          <Form :label-width="140">
            <FormItem label="请选择测试音箱：">
              <RadioGroup v-model="checkSpeakerPort">
                <Radio :label="item.port" v-for="(item, index) in online_speaker" :key="index">
                  <Badge>
                    <Dropdown>
                      <Avatar :style="{background: item.device_type === 0 ? '#f56a00' : '#7265e6'}">
                        {{ item.device_type === 0 ? 'ADB' : '串口' }}
                      </Avatar>
                      <DropdownMenu slot="list" style="text-align: center">
                        <DropdownItem>{{ item.port }}</DropdownItem>
                      </DropdownMenu>
                    </Dropdown>
                    <Icon type="ios-radio-button-on" slot="count" :color="item.run_status === 1 ? '#ed4014' : '#19be6b'" size="16" />
                  </Badge>
                </Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </i-col>
      </Row>
    </Modal>

    <Modal
        v-model="addModal"
        title="新增巡检任务"
        width="720"
        footer-hide>
      <Form ref="addTaskForm" :model="TaskForm" :rules="ruleValidate" :label-width="150">
        <FormItem label="任务标题" prop="title">
          <Input v-model="TaskForm.title" placeholder="请输入任务标题"></Input>
        </FormItem>
        <FormItem label="请选择产品类型" prop="task_type">
          <Select v-model="TaskForm.task_type" placeholder="请选择产品类型">
            <Option v-for="(item, index) in product_list" :key="index" :value=item.id>{{ item.speaker_name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="请勾选测试用例" prop="testcase">
          <CheckboxGroup v-model="TaskForm.testcase">
            <Checkbox v-for="(item, index) in modules" :key="index" :label="item.id" >{{item.module_name}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="请选择用例类型" prop="is_smoke">
          <RadioGroup v-model="TaskForm.is_smoke">
            <Radio label="true">仅限冒烟</Radio>
            <Radio label="false">全量用例</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="请选择测试方式" prop="run_type">
          <RadioGroup v-model="TaskForm.run_type">
            <Radio :label="1">反控接口测试</Radio>
            <Radio :label="2">非开启VAD测试</Radio>
            <Radio :label="3">语音唤醒测试</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="写一段任务简介" prop="desc">
          <Input v-model="TaskForm.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="输入点儿什么东西吧..."></Input>
        </FormItem>
      </Form>
      <Row>
        <Col flex="auto">
        </Col>
        <Col flex="160px">
          <Button @click="handleReset('addTaskForm')" style="margin-left: 8px">清空</Button>
          <Button type="primary" @click="handleSubmit('addTaskForm')">提交</Button>
        </Col>
      </Row>
    </Modal>
  </div>
</template>

<script>
export default {
  name: "TaskList",
  data() {
    return {
      loadingTag: true,
      checkSpeakerPort: '',
      online_speaker: [],
      product_list: [],
      modules: [],
      task_list: [],
      addModal: false,
      selectSpeakerModal: false,
      tmp_id: 0,
      TaskForm: {
        'title': '',
        'task_type': 0,
        'testcase': [],
        'is_smoke': "true",
        'run_type': 1,
        'desc': ''
      },
      ruleValidate: {
        title: [
          { required: true, message: '请输入一个合适的任务标题吧', trigger: 'blur' }
        ],
        task_type: [
          { required: true, type:'number', message: '请选择音箱类型', trigger: 'change' }
        ],
        testcase: [
          { required: true, type: 'array', message: '请勾选测试用例', trigger: 'change' }
        ],
        is_smoke: [
          { required: true, message: '请选择用例类型', trigger: 'change' }
        ],
        run_type: [
          { required: true,type: 'number', message: '请选择运行方式', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '至少得输入一点儿东西吧', trigger: 'blur' },
          { type: 'string', min: 1, message: '至少得输入一点儿东西吧', trigger: 'blur' }
        ]
      },
    }
  },
  watch: {
    'TaskForm.task_type':function(newValue, oldValue){
      this.TaskForm.testcase = []
      let s_info = sessionStorage.getItem('module_info')
      // 从sessionStorage中读取数据，遍历数据
      JSON.parse(s_info).forEach(item=>{
        if (item.id === newValue){
          this.modules = item.modules
        }
      })
    }
  },
  mounted() {
    // 获取任务列表
    this.$getRequest('/task/').then(response=>{
      if (response.status === 200){
        this.task_list = response.data
        console.log(this.task_list)
      }
    }).catch(error=>{
      console.log(error)
    })
    this.getOnlineSpeaker()
  },
  methods: {
    getOnlineSpeaker(){
      // 获取所有在线设备列表
      this.$getRequest('/speakerDetail/').then(response=>{
        this.online_speaker = response.data
      }).catch(error=>{
        console.log(error)
      })
    },
    onClickGetProductInfo() {
      // 获取产品列表
      this.$getRequest('/speakerProduct').then( response => {
        if (response) {
          //  这里需要使用vuex来保存response数据，这里为了方便，直接放在sessionStorage里面了
          sessionStorage.setItem('module_info', JSON.stringify(response.data))
          this.product_list = response.data

          this.handleReset('addTaskForm')
          this.addModal = true
        }
      }).catch( error => {
        console.log(error)
      });
    },
    onClickExecuteTask(id){
      this.selectSpeakerModal = true
      this.tmp_id = id
    },
    executeTask (port) {
      let sys_version = 0
      this.online_speaker.forEach(item=>{
        if (item.port === port){
          sys_version = item.device_type
        }
      })

      let data = {
        "task_id": this.tmp_id,
        "port": port,
        "sys_version": sys_version
      }
      console.log(data)
      // 执行测试任务
      this.$postRequest(`/task/execute/`, data).then(response=>{
        if (response.status === 200){
          console.log(response.data.message)
          this.selectSpeakerModal = false
          location.reload()
        }
      }).catch(error=>{
        console.log(error)
      })
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 添加巡检任务
          console.log(this.TaskForm)
          this.$postRequest('/task/add/', this.TaskForm).then(response=>{
            if (response.status === 200){
              this.addModal = false
              location.reload()
            }
          }).catch(error=>{
            console.log(error)
          })

        } else {
          this.$Message.error('参数填写错误，请重新填写！');
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields();
    },
    select_online_speaker(sys){
      let data = []
      // 遍历数据
      this.online_speaker.forEach(item=>{
        if (item.device_type === sys){
          data.push(item)
        }
      })
      return data
    },
    select_title(status){
      switch (status){
        case 0:
          return "未运行"
        case 1:
          return "运行中"
        case 2:
          return "已完成"
      }
    },
    select_color(status){
      switch (status){
        case 0:
          return "#2db7f5"
        case 1:
          return "#ff9900"
        case 2:
          return "#19be6b"
      }
    }
  }
}
</script>

<style scoped>
.title{
  font-size: 16px;
  font-weight: bolder;
}
</style>